using System.Collections.Generic;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.Logic;
using LFloatMath.Collision2D;
using LFloatMath.Math;
using NetProtocol.POD;
using UnityEditor;
using UnityEngine;
using Random = UnityEngine.Random;

namespace IQIGame.Onigao.GamePlay.Editors
{
    public class BattleTestWindow : EditorWindow
    {
        private static BattleTestWindow _instance;

        public static BattleTestWindow Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = CreateWindow<BattleTestWindow>("BattleTest");
                }
                return _instance;
            }
        }

        [MenuItem("GameEditor/BattleDebug/BattleTestWindow", false, 100)]
        public static void Open()
        {
            Instance.Show();
        }

        private void OnInspectorUpdate()
        {
            Repaint();
        }

        private BattleData _BattleData => BattleManager.Instance.ctrl.data;

        private string s1;
        private string s2;
        private string s3;
        private string s11;
        private string s21;
        private string s31;

        private Formula f;

        public int tempInt;

        private string ssss;
        private Vector3 v1;
        private Vector3 v2;
        private Vector3 v3;

        private float ff;

        private List<ColliderProxy> proxys = new List<ColliderProxy>();
        ColliderProxy tempProxy;
        private GameObject go;
        private List<ColliderProxy> onHit = new List<ColliderProxy>();

        private Vector2 commandViewScrol;

        private void OnGUI()
        {
            // 碰撞测试
            // if (BattleEditorTools.FloatField("x1", ref v1.x) ||
            //     BattleEditorTools.FloatField("y1", ref v1.z) ||
            //     BattleEditorTools.FloatField("x", ref v2.x) ||
            //     BattleEditorTools.FloatField("y", ref v2.z) ||
            //     BattleEditorTools.FloatField("posx", ref v3.x) ||
            //     BattleEditorTools.FloatField("posy", ref v3.z))
            // {
            //     if (tempProxy == null) 
            //     {
            //         v1.y = 0; 
            //         v2.y = 0;
            //         go = GameObject.CreatePrimitive(PrimitiveType.Cube);
            //         go.transform.localScale = v1;
            //         go.transform.position = v2;
            //         
            //         tempProxy = ColliderProxy.Fetch();
            //         tempProxy.Init(CollisionUtil.GetCubePrefab((v1.x/2).ToLFloat(),(v1.z / 2).ToLFloat(), LVector2.up),
            //             v3.ToLVector2XZ()); 
            //     }
            //     go.transform.localScale = v1;
            //     go.transform.position = v3;
            //     go.transform.rotation = Quaternion.LookRotation(v2);
            //     ColliderProxy rProxy = this.tempProxy;
            //     rProxy.deg = LMath.AngleIntUp(v2.ToLVector2XZ().normalized);
            //     rProxy.pos = v3.ToLVector2XZ();
            //     this.onHit.Clear();
            //     for (int i = 0; i < this.proxys.Count; i++)
            //     { 
            //         var a = rProxy;
            //         var b = this.proxys[i]; 
            //         bool isCollided = a != b && CollisionHelper.CheckCollision(a.Prefab, a.Transform2D, b.Prefab, b.Transform2D);
            //         if (isCollided)
            //         {
            //             this.onHit.Add(b); 
            //         }
            //     }
            // }
            // ssss = EditorGUILayout.TextField("Count:", this.onHit.Count.ToString());
            // if (GUILayout.Button("Clear"))
            // {
            //     for (int i = 0; i < this.proxys.Count; i++)
            //     {
            //         ColliderProxy.Free(this.proxys[i]);
            //     }
            //     this.proxys.Clear();
            //     ColliderProxy.Free(this.tempProxy);
            //     if (this.go)
            //     {
            //         GameObject.DestroyImmediate(this.go);
            //     }
            //     this.onHit.Clear();
            // }
            // if (GUILayout.Button("添加初始"))
            // {
            //     for (int i = 0; i < 6; i++)
            //     {
            //         var rGo = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            //         rGo.transform.position = new Vector3(i / 3 * 1.5f, 0, i % 3 * 2f);
            //
            //         var rProxy = ColliderProxy.Fetch();
            //         rProxy.Init(CollisionUtil.GetCirclePrefab(LFloat.half), rGo.transform.position.ToLVector2XZ());
            //         this.proxys.Add(rProxy);
            //     }
            // }


            if (!EditorApplication.isPlaying || BattleManager.Instance.ctrl == null)
            {
                return;
            }

            EditorGUILayout.BeginHorizontal();
            {
                if (BattleEditorTools.Button("测试"))
                {
                    var rData = BattleManager.Instance.ctrl.data;
                    var rDeadUnit = rData.units.Find((x) => x.GetComponent<DeadViewComponent>(ETComponentType.DeadViewComponent) != null);
                    BattleManager.Instance.Substitute(rDeadUnit.GUID);
                }

                EditorGUILayout.BeginVertical();
                if (BattleEditorTools.Button("初始化"))
                {
                    HUDNumberRender.Instance.Initialize(PathConstant.GetHUDConfigPath());
                }
                if (BattleEditorTools.Button("结束"))
                {
                    HUDNumberRender.Instance.Dispose();
                }

                BattleEditorTools.IntField("值", ref tempInt);
                if (BattleEditorTools.Button("展示"))
                {
                    HUDNumberRender.Instance.AddHudNumber(new Vector3(0, 0, 0), Vector3.zero, (int)EHUDNumberRenderType.NormalHurt, Random.Range(100, 1000), Color.white);
                }

                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical(GUILayout.Width(330));
                if (BattleEditorTools.Button("选择目标"))
                {
                    var rRandomUnit = _BattleData.units[UnityEngine.Random.Range(0, _BattleData.units.Count)];

                    BattleManager.Instance.Cast(new BattleSkillPOD()
                    {
                        targetId = rRandomUnit.GUID,
                        skillId = 1
                    });
                }

                BattleEditorTools.TextField("输入", ref s1);
                BattleEditorTools.TextField("输出", ref s2);
                BattleEditorTools.TextField("结果", ref s3);
                if (BattleEditorTools.Button("计算"))
                {
                    //string inputStr = Console.ReadLine();
                    string teststr = s1;
                    var rToken = new Formula().Initialize(teststr);
                    s2 = "";
                    foreach (object str in rToken.rePolish)
                    {
                        s2 += string.Format("[{0}], ", str);
                    }

                    //计算公式的值
                    if (rToken.Calculate<LFloat>(out var result, null, null))
                    {
                        s3 = result.ToString();
                    }

                    rToken.Dispose();
                    // int resultValue = FormulaTest.calculateExpression(changeSt);
                    // s3 = string.Format("{0} = {1} ", teststr ,resultValue);
                }

                BattleEditorTools.TextField("输入", ref s11);
                BattleEditorTools.TextField("输出", ref s21);
                BattleEditorTools.TextField("结果", ref s31);
                if (BattleEditorTools.Button("计算"))
                {
                    string teststr = s11;
                    if (f == null)
                    {
                        f = new Formula().Initialize(teststr);
                    }

                    var rToken = f;

                    s21 = "";
                    foreach (object str in rToken.rePolish)
                    {
                        s21 += string.Format("[{0}], ", str);
                    }

                    //计算公式的值
                    if (rToken.Calculate<bool>(out var result))
                    {
                        s31 = result.ToString();
                    }

                    // rToken.Dispose();
                }

                if (BattleEditorTools.Button("清理"))
                {
                    f?.Dispose();
                    f = null;
                    FormulaHelper.ClearPool();
                }

                if (BattleEditorTools.FloatField("distance:", ref ff))
                {
                    BattleManager.Instance.ctrl.sceneCtrl.SetMainCameraDistance(ff);
                }
                EditorGUILayout.EndVertical();
            }

            {
                EditorGUILayout.BeginHorizontal(GUILayout.Width(500));
                EditorGUILayout.BeginVertical();
                var rQueue = BattleManager.Instance.ctrl?.queueCtrl;
                if (rQueue == null)
                {
                    return;
                }

                if (rQueue.curCmd != null)
                {
                    EditorGUILayout.LabelField(rQueue.curCmd.ToString());
                    EditorGUILayout.LabelField("---------");
                }

                if (rQueue.Queue != null)
                {
                    foreach (var rView in rQueue.Queue)
                    {
                        EditorGUILayout.LabelField(rView.ToString());
                    }
                }

                EditorGUILayout.EndVertical();
                EditorGUILayout.EndHorizontal();
            }

            {
                EditorGUILayout.BeginVertical();
                this.path = EditorGUILayout.TextField(path);
                if (GUILayout.Button("111"))
                {
                    this.iiii = (this.iiii + 1) % this.ss.Length; 
                    LoadTest(string.IsNullOrEmpty(this.path) ? ss[this.iiii] : this.path);
                }
                EditorGUILayout.EndVertical();
            }

            EditorGUILayout.EndHorizontal();
        }

        private int iiii;
        private string[] ss = new string[]
        {
            "Res/02_Character/Lead_suit_LH/Timeline/Lead_suit_female_uskill.playable",
            "Res/02_Character/Lead_suit_LH/Timeline/Lead_suit_female_attack.playable",
            "Res/03_Prefabs/Entity/monster_WrathF001/Timeline/WrathF001_Timeline_skill01.playable",
            "Res/02_Character/Poiro_detective/Timeline/Poiro_Timeline_skill1.playable",
            "Res/02_Character/Poiro_detective/Timeline/Poiro_Timeline_skill2.playable",
            "Res/02_Character/Lead_suit_LH/Timeline/Lead_suit_female_skill1.playable",
            "Res/02_Character/YuMingTong_bee/Timeline/YuMingTong_bee_skill1.playable",
            "Res/03_Prefabs/Entity/monster_WrathF001/Timeline/WrathF001_Timeline_attack.playable",
            "Res/03_Prefabs/Entity/monster_BoarM001/Timeline/M_BoarM001_skill1.playable",
            "Res/03_Prefabs/Entity/monster_BoarM001/Timeline/M_BoarM001_skill2.playable",
            "Res/03_Prefabs/Entity/monster_BoarM001/Timeline/M_BoarM001_uskill.playable",
        };
        
        async void LoadTest(string path)
        {
            var r = await ManagerCenter.Timeline.Get(path);
            if (r.asset)
            {
                Debug.Log(r.asset.name);
            }
            else
            {
                LogGame.LogError(path);
            }
        }
        
        private string path;
    }
}